package threads;

import java.util.ArrayList;
import java.util.List;

public class FixedCntBoxTest_WaitNotify<T> {
    private volatile int count;
    private static final int MAX_CNT = 10;
    private final List<T> list = new ArrayList<>();

    public synchronized void put(T t) {
        while (count >= MAX_CNT) {
            notifyAll();
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        count++;
        list.add(t);
    }

    public synchronized T get() {
        while (count <= 0) {
            try {
                notifyAll();
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        count--;
        return list.remove(list.size() - 1);
    }

    public static void main(String[] args) {
        FixedCntBoxTest_WaitNotify<String> list = new FixedCntBoxTest_WaitNotify<>();
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                while (true) {
                    String s = list.get();
                    System.out.println(Thread.currentThread().getName() + "消费:" + s);
                }
            }, "消费者" + i).start();
        }
        for (int i = 0; i < 2; i++) {
            new Thread(() -> {
                int cnt = 0;
                while (true) {
                    String tName = Thread.currentThread().getName();
                    String pName = tName + "产品" + (cnt++);
                    list.put(pName);
                    System.out.println("生产者" + tName + "生产产品：" + pName);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }, "t" + i).start();
        }
    }
}
